package br.edu.ufcg.dsc.actions.user;

import javax.persistence.EntityTransaction;

import org.apache.struts2.config.Result;
import org.apache.struts2.dispatcher.ServletRedirectResult;

import br.edu.ufcg.dsc.services.UserService;

@Result(name = "success", type = ServletRedirectResult.class, value = "/index.action")
public class UpdateAction extends BaseUserAction {

	private static final long serialVersionUID = -4905259593769313198L;
	
	public String execute() {
		EntityTransaction tx = null;
		try {
			tx = entity.getTransaction();
			tx.begin();

			if ("".equals(loginId)) {
				entity.persist(user);
			} else {
				entity.merge(user);
			}
			tx.commit();
		} catch (Exception e) {
			if (tx != null && tx.isActive())
				tx.rollback();
				e.printStackTrace();
		}
		return SUCCESS;
	}
	
	public void validate(){
		if(!(loginId.equals(user.getLogin())) && (UserService.find(user.getLogin()) != null)){
			addFieldError("login", "user.already.exists");
		}
	}
}
